package com.epoint.mobileoa.tools.download;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.text.Html;
import android.widget.Toast;

/**
 * @author liyc
 * @time 2013-3-27 下午1:40:40
 * @annotation 新的下载线程
 */
public class DownloadThread extends Thread{

	Context con;
	Handler handler;
	ProgressDialog progressDialog;
	int total = 0;
	String savePath;
	String urlStr;
	public DownloadThread(Context con,String _urlStr,String filePath)
	{
		this.con = con;
		handler = new Handler();
		progressDialog = new ProgressDialog(con);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		savePath = filePath;
		
		String[] urlelements = _urlStr.split("/");
		String lastElement = urlelements[urlelements.length-1];
		String encodeLastElement = URLEncoder.encode(lastElement);
		_urlStr = _urlStr.replaceAll(lastElement, encodeLastElement);
		this.urlStr = _urlStr;
	}

	@Override
	public void run() {
		try{
			URL url = new URL(urlStr);
			URLConnection conexion = url.openConnection();
			final long fileLength = conexion.getContentLength();
			
			File destFile = new File(savePath);
			if (destFile.length()==fileLength) {
				return;
			}
			
			if (fileLength==0) {
				throw new Exception("Server File is Null");
			}
			
			handler.post(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					progressDialog.show();
				}
			});
			
			
			int count;
			InputStream input = conexion.getInputStream();
			OutputStream output = new FileOutputStream(
					savePath+".temp");
			
			total = 0;
			byte data[] = new byte[1024];
			while ((count = input.read(data)) != -1) {
				total += count;
				output.write(data, 0, count);
				handler.post(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						progressDialog.setProgress((int) ((total * 100) / fileLength));
						File f = new File(savePath+".temp");
						if (f.length()==fileLength) {
							progressDialog.dismiss();
							Move(savePath+".temp", savePath);
						}
					}
				});
			}
			output.flush();
			output.close();
			input.close();
		}catch(Exception e)
		{
			final Exception ee = e;
			e.printStackTrace();
			handler.post(new Runnable() {

				@Override
				public void run() {
					Toast.makeText(con, Html.fromHtml("下载失败<br><font color=red>"+ee.getMessage()+"</font>"), Toast.LENGTH_LONG).show();
					progressDialog.dismiss();
				}
			});
		}
	}
	
	public static boolean Move(String srcFile, String destPath)
	 {
	        File file = new File(srcFile);
	        File destFile = new File(destPath);
	        if(destFile.exists())
	        {
	        	destFile.delete();
	        }
	        boolean success = file.renameTo(new File(destPath));
	        return success;
	 }
}
